package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.place;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.statistics.dao.db.PlaceDayStatistics;
import com.gzhryc.shared_device.oem.code.statistics.services.PlaceDayStatisticsService;
import com.gzhryc.shared_device.oem.code.statistics.services.dao.PlaceDayStatisticsSearch;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

public class PlaceStatisticsController {

    static Logger log = Logger.getLogger(PlaceStatisticsController.class);

    @Route(value = { "/place/statistics/index.html" })
    public String list(HttpServletRequest request) {
        String searchDate = DateFormatUtils.format(new Date(),"yyyy-MM-dd");
        request.setAttribute("searchDate",searchDate);
        return "/place/statistics/index.html";
    }

    @Route(value = "/place/statistics/day/list.data")
    public ListResult<PlaceDayStatistics> listData(HttpServletRequest request) {
        ListResult<PlaceDayStatistics> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PlaceDayStatisticsSearch search = WebUtils.getParameter(request, PlaceDayStatisticsSearch.class);
        if(search != null && search.getPlaceId() != null){
            Integer pageNo = WebUtils.getInteger(request, "page", 1);
            Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
            String searchDate = WebUtils.getString(request, "searchDate");
            try {
                Date date = null;
                if (StringTools.isNotBlank(searchDate)) {
                    date = DateUtils.parseDate(searchDate, "yyyy-MM-dd");
                } else {
                    date = new Date();
                }
                String dayDate = DateFormatUtils.format(date, "yyyyMMdd");
                search.setDayDate(dayDate);

                result.getBody().setTotal(PlaceDayStatisticsService.self().countBySearch(search));
                List<PlaceDayStatistics> dayStatisticsList = PlaceDayStatisticsService.self().findBySearch(search, pageNo, pageLimit);
                if (dayStatisticsList != null && dayStatisticsList.size() > 0) {
                    result.setCode(DtoConstants.SUCCESS, null);
                    result.getBody().setData(dayStatisticsList);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return result;
    }
}
